<?php

namespace Acme\SecurityBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;


// AcmeSecurityBundle_AjaxValidate
use Symfony\Component\Validator\Validator;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;


// AcmeSecurityBundle_JsConstraintsGenerator
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\IndexedReader;

use Symfony\Component\Validator\Constraints;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

use Acme\UserBundle\Entity\CmUser;
use Acme\UserBundle\Entity\CmUserInfo;
use Acme\CommonBundle\Entity\ConstUniversity;
use Acme\ContestBundle\Entity\CtInfo;

use Acme\UserBundle\Form\UserInfoType;
use Acme\UserBundle\Form\UserCreateType;


class JsValidatorController extends Controller
{
    /**
     * @Route("/js_constraints_generator/{form}/{options}", defaults={"form" = "", "options" = ""}, name="AcmeSecurityBundle_JsConstraintsGenerator")
     * @Template()
     */
    public function jsConstraintsGeneratorAction($form, $options)
    {	
    	//$options['entity']['parent'] = 'CmUser';
    	//$entity['child'] = 'CmUser';
    	$entity = $options['entity'];
    	foreach ($entity as $k => $v) {
    		switch ($v) {
    			case 'CmUser':
    			case 'CmUserInfo':
    			case 'CmAdminInfo':
    				$entity[$k] = '\\Acme\\UserBundle\\Entity\\' . $v;
    				break;
    			case 'ConstUniversity':
    			case 'ConstArea':
    				$entity[$k] = '\\Acme\\CommonBundle\\Entity\\' . $v;
    				break;
    			case 'CtInfo':
    				$entity[$k] = '\\Acme\\ContestBundle\\Entity\\' . $v;
    				break;
    		}
    	}
    	
    	/*$user = new CmUser();
    	
    	$buildOption['category_name'] = 'admin';
    	$buildOption['build_for'] = 'create';
    	$options['ignore'] = array('adminCategory', 'userCategory');
    	$form = $this->createForm(new UserCreateType(), $user, $buildOption);*/
    	
    	$form_children = $form->getChildren();  // $form->createView()->getChildren();
    	//echo "<pre>";
    	//print_r($form_children);
    	//return ;
    	$ignore = array();
    	if (isset($options['ignore'])) {
    		$ignore = $options['ignore'];
    	}
    	
    	foreach ($form_children as $k => $form_child) {
    		if ($k != '_token' && !in_array($k, $ignore)) {
    			//echo $k . "<br />";
    			//print_r($form_child);
    			if ($form_child->hasChildren()) {
    				foreach ($form_child->getChildren() as $k => $v) {
    					//print_r($v->get('full_name'));
    					//echo "<br />";
    					$entity_property_list[$entity['child']][$v->get('name')] = $v->get('full_name');
    					if ($v->get('name') == 'password') {
    						$entity_property_list[$entity['child']][$v->get('name')] = array($v->get('full_name') . '[first]', $v->get('full_name') . '[second]');
    					}
    				}
    				
    			} else {
    				//print_r($form_child->get('full_name'));
    				//echo "<br />";
    				$entity_property_list[$entity['parent']][$form_child->get('name')] = $form_child->get('full_name');
    				if ($form_child->get('name') == 'password') {
    					$entity_property_list[$entity['parent']][$form_child->get('full_name')] = array($form_child->get('full_name') . '[first]', $form_child->get('full_name') . '[second]');
    				}
    			}
    		} elseif (in_array($k, $ignore)) {
    			//echo "<pre>";
    			//print_r($form_child->get('full_name'));
    			$rules[$form_child->get('full_name')]['required'] = 1;
    			$messages[$form_child->get('full_name')]['required'] = '请选择' . $form_child->get('label');
    		}
    	}
    	
    	//echo "<pre>";
    	//print_r($entity_property_list);
    	//return ;
    	
    	$reader = new AnnotationReader();
    	
    	foreach ($entity_property_list as $entity => $property) {
    		foreach ($property as $property_name => $full_name) {
				$reflProperty = new \ReflectionProperty($entity, $property_name);
				$propertyAnnotations = $reader->getPropertyAnnotations($reflProperty);
				
				if (!is_array($full_name)) {
					foreach ($propertyAnnotations as $annot) {
						if ($annot instanceof Constraints\NotBlank) {
							$propertyConstraints[$full_name]['rules']['required'] = true;
							$propertyConstraints[$full_name]['messages']['required'] = $annot->message;
						} elseif ($annot instanceof Constraints\MinLength) {
							$propertyConstraints[$full_name]['rules']['minlength'] = $annot->limit;
							$propertyConstraints[$full_name]['messages']['minlength'] = str_replace('{{ limit }}', $annot->limit, $annot->message);
						} elseif ($annot instanceof Constraints\MaxLength) {
							$propertyConstraints[$full_name]['rules']['maxlength'] = $annot->limit;
							$propertyConstraints[$full_name]['messages']['maxlength'] = str_replace('{{ limit }}', $annot->limit, $annot->message);
						} elseif ($annot instanceof Constraints\Regex) {
							$propertyConstraints[$full_name]['rules']['pattern'] = str_replace('/', '', $annot->pattern);
							$propertyConstraints[$full_name]['messages']['pattern'] = $annot->message;
						} elseif ($annot instanceof Constraints\Email) {
							$propertyConstraints[$full_name]['rules']['email'] = true;
							$propertyConstraints[$full_name]['messages']['email'] = $annot->message;
						}
					}
				} else {
					$full_name_first = $full_name[0];
					$full_name_second = $full_name[1];
					foreach ($propertyAnnotations as $annot) {
						if ($annot instanceof Constraints\NotBlank) {
							$propertyConstraints[$full_name_first]['rules']['required'] = true;
							$propertyConstraints[$full_name_first]['messages']['required'] = $annot->message;
						} elseif ($annot instanceof Constraints\MinLength) {
							$propertyConstraints[$full_name_first]['rules']['minlength'] = $annot->limit;
							$propertyConstraints[$full_name_first]['messages']['minlength'] = str_replace('{{ limit }}', $annot->limit, $annot->message);
						} elseif ($annot instanceof Constraints\MaxLength) {
							$propertyConstraints[$full_name_first]['rules']['maxlength'] = $annot->limit;
							$propertyConstraints[$full_name_first]['messages']['maxlength'] = str_replace('{{ limit }}', $annot->limit, $annot->message);
						} elseif ($annot instanceof Constraints\Regex) {
							$propertyConstraints[$full_name_first]['rules']['pattern'] = str_replace('/', '', $annot->pattern);
							$propertyConstraints[$full_name_first]['messages']['pattern'] = $annot->message;
						} elseif ($annot instanceof Constraints\Email) {
							$propertyConstraints[$full_name_first]['rules']['email'] = true;
							$propertyConstraints[$full_name_first]['messages']['email'] = $annot->message;
						}
					}
					$propertyConstraints[$full_name_second] = $propertyConstraints[$full_name_first];
					$propertyConstraints[$full_name_second]['rules']['compareTo'] = $full_name_first;
					$propertyConstraints[$full_name_second]['messages']['compareTo'] = '两次输入密码不一致';
				}
				
				 
				/*$reflClass = new \ReflectionClass($entity);
				 $classAnnotations = $reader->getClassAnnotations($reflClass);
				//echo "<pre>";
				//print_r($classAnnotations);
				foreach ($classAnnotations as $annot) {
				if ($annot instanceof UniqueEntity && $annot->fields == $property_name) {
				$propertyConstraints[$full_name]['rules']['ajax'] = $this->generateUrl('AcmeSecurityBundle_AjaxValidate');
				$propertyConstraints[$full_name]['messages']['ajax'] = $annot->message;
				}
				}*/
    		}
    	}
    	
    	//echo "<pre>";
    	//print_r($propertyConstraints);
    	//return ;
    	
    	foreach ($propertyConstraints as $k => $v) {
    		$rules[$k] = $v['rules'];
    		$messages[$k] = $v['messages'];
    	}
    	
    	$data = array('rules' => $rules, 'messages' => $messages);
    	
    	//echo "<pre>";
    	//print_r($data);
    	//return ;
    	return array('form' => $form, 'data' => json_encode($data));
    }
    
    /**
     * @Route("/ajax_validate", name="AcmeSecurityBundle_AjaxValidate")
     * @Template()
     */
    public function ajaxValidateAction()
    {
    	$request = $this->get('request');
    	$param = $request->get('param');
    	
    	$param[0] = 'CmUser';
    	$param[1] = 'username';
    	$param[2] = 'stu_01!';
    	$param[3] = 'regist_default';
    	
    	switch ($param[0]) {
    		case 'CmUser':
    		case 'CmUserInfo':
    		case 'CmAdminInfo':
    			$entity = '\\Acme\\UserBundle\\Entity\\' . $param[0];
    			break;
    		case 'ConstUniversity':
    			$entity = '\\Acme\\CommonBundle\\Entity\\' . $param[0];
    			break;
    	}
    	
    	$validator = $this->get('validator');
    	$errors = $validator->validatePropertyValue($entity, $param[1], $param[2], explode(', ', $param[3]));    	
    	
    	/*$uev = new UniqueEntityValidator();
    	
    	echo "<pre>";
    	print_r($uev);
    	return ;*/
    	
    	return array('errors' => $errors, 'field_id' => $param[4]);
    }
}
